package com.onpositive.wiki3.db.catmodel.matches.classify;

import java.util.ArrayList;

import com.onpositive.nlp.sequence.ClassifiedSequence;
import com.onpositive.nlp.sequence.ClassifiedSequence.Token;
import com.onpositive.wiki3.db.catmodel.Categories;
import com.onpositive.wiki3.db.catmodel.Category;
import com.onpositive.wiki3.db.impl.CountingVocabalary;
import com.onpositive.wiki3.db.impl.CountingVocabalary.Pair;

public class BestParentsMatcher extends AbstractRecordingMatcher {

	public BestParentsMatcher(RelationStore store) {
		super(store);
	}

	public String getCoreString(Category st) {
		ClassifiedSequence core = getCore(st);
		Token core2 = core.getCore();
		if (core2 != null) {
			return core2.name;
		}
		return null;
	}

	@Override
	public int accept(Category st) {
		Categories categories = toRecord.get(RelationConstants.IS_A);
//		if (categories.get(st.id())!=null){
//			//already known;
//			return 0;
//		}
		Category[] parentsCategories = st.getParentsCategories();
		
		if (parentsCategories.length==1){
			record(RelationConstants.IS_A, parentsCategories[0], st);
			return 0;
		}
		CountingVocabalary m = new CountingVocabalary();
		ClassifiedSequence ll = getCore(st);
		Token pcore = ll.getCore();
		if (pcore==null){
			return 0;
		}
		
		for (Category c : parentsCategories) {
			ClassifiedSequence coreString = getCore(c);
			Token core = coreString.getCore();
			if (core != null) {
				if(pcore.verb){
					if (core.noun&&!pcore.noun){
						continue;
					}
				}
				else if (core.verb){
					continue;
				}
				if (coreString.isClassification()){
					m=new CountingVocabalary();
					m.add(core.name,4);					
					break;
				}	
				m.add(core.name);
				
				if (core.plural) {
					m.add(core.name);
					if (core.name.equals(c.toString())) {
						m.add(core.name);
						m.add(core.name);
					}
				}
			}
		}
		ArrayList<Pair> all = m.all();
		String best = null;
		for (Pair p : all) {
			best = p.s;
			if (p.i>=2){
				for (Category c : parentsCategories) {
					ClassifiedSequence coreString = getCore(c);
					Token core = coreString.getCore();
					if (core != null) {
						if (core.name.equals(best)) {
							record(RelationConstants.IS_A, c, st);
						}
					}
				}	
			}			
		}		
		return 0;
	}

}
